package com.ingenio.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ingenio.business.Marca;
import com.ingenio.dao.MarcaAdapter;

/**
 * Servlet implementation class ABMMarcasServlet
 */
@WebServlet("/ABMMarca")
public class ABMMarcasServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ABMMarcasServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String descripcion = "";
		MarcaAdapter ma = new MarcaAdapter();
		Marca m = null;
		if("delete".equals(request.getParameter("type"))){
			try {
				Integer id = Integer.parseInt(request.getParameter("id"));
				m = ma.devolverMarca(id);
		    	ma.eliminarMarca(m);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if("edit".equals(request.getParameter("type"))){
			if(request.getParameter("descripcion_marca") != null && request.getParameter("id_marca_hidden") != null){
				descripcion = request.getParameter("descripcion_marca");
				Integer id = Integer.parseInt(request.getParameter("id_marca_hidden"));
				try {
					m = ma.devolverMarca(id);
					m.setDescMarca(descripcion);
					ma.modificarMarca(m);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else if("add".equals(request.getParameter("type"))){
			if(request.getParameter("descripcion_marca") != null){
				descripcion = request.getParameter("descripcion_marca");
				try {
					m = new Marca(null, descripcion, true);
					ma.agregarMarca(m);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		response.sendRedirect("marcas/listado_marcas.jsp");
	}
}
